//
//  ClinicalCollectionsViewController.m
//  ClinicalCollections
//
//  Created by janakiraman gopinath on 12/29/12.
//  Copyright (c) 2012 GOPI. All rights reserved.
//

#import "ClinicalCollectionsViewController.h"
#import "CommonAPI.h"
#import "CCViewStudyViewController.h"


@interface ClinicalCollectionsViewController ()
@property (weak, nonatomic) IBOutlet UISegmentedControl *uiMapTerrainType;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *uiView;
@property (nonatomic, weak) UIBarButtonItem *barButtonItem;
@property (nonatomic, weak) UIPopoverController *popOverController;
@property (nonatomic, weak) GraphViewController *clinicalTrialWebViewController;

@end


@implementation ClinicalCollectionsViewController
@synthesize barButtonItem = _barButtonItem;
@synthesize mapView = _mapView;
@synthesize uiView = _uiView;
@synthesize clinicalTrialWebViewController  = _clinicalTrialWebViewController;
@synthesize uiMapTerrainType = _uiMapTerrainType;
@synthesize searchEnable = _searchEnable;
@synthesize search = _search;


- (void)awakeFromNib {
    [super awakeFromNib];
    self.splitViewController.delegate = self;
    self.mapView.delegate = self;
    
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    GenericTableViewController *gvc = [[CommonAPI  class] targetViewControllerFrom:self
                                                                           forPath:CLINICALTRIALGOV
                                                                              side:LEFT
                                                           returningViewController:GENERICVIEWCONTROLLER];
    
    // Update the map with the latest depending on the selection made outside of the map view e.g. GraphView or
    // WebView etc (mostly when returning from those views by back button)
    
    if (gvc && ![gvc isEqual:[NSNull null]] &&
        [gvc isKindOfClass:GENERIC_VIEW_CONTROLLER_CLASS] &&
        gvc.tableView.window)
    {
        [gvc refreshMap:self forIndexPath:[gvc.tableView indexPathForSelectedRow]];
        [self hideSearchBar:NO];
    }
    
    // Search bar should not show when the search view controller is active show only when the generic view controller is active
    else
    {
        [self hideSearchBar:YES];
    }
    
    
}
- (void) viewDidLoad
{
    [super viewDidLoad];
    self.accessoryEnabled = YES;
    
}

#pragma mark -- UISearhBarDelegate

-(void)hideSearchBar:(BOOL)hidden
{
    if (!self.navigationItem.titleView ||
        (self.navigationItem.titleView && ![self.navigationItem.titleView isKindOfClass:[UISearchBar class]])) {
        self.navigationItem.titleView =  [[UISearchBar alloc] init];
        ((UISearchBar *)self.navigationItem.titleView).delegate = self;
    }
    [self.navigationItem.titleView setHidden:hidden];
/*
 //the following code was added to allow for an additional button when on the search screen
 //it no longer appears to be necessary so I'm disabling.
    if (!hidden) {
        //if we have a bar button item, we need to switch it back in
        //when it should not be hidden
        if ([self.navigationItem.rightBarButtonItems count] > 1) {
            self.navigationItem.rightBarButtonItems = @[self.navigationItem.rightBarButtonItem];
            // Setup UI Search BAR, could have done it from stoary board also.
            if (!self.navigationItem.titleView ||
                (self.navigationItem.titleView && ![self.navigationItem.titleView isKindOfClass:[UISearchBar class]])) {
                self.navigationItem.titleView =  [[UISearchBar alloc] init];
                ((UISearchBar *)self.navigationItem.titleView).delegate = self;
                [self.navigationItem.titleView setHidden:hidden];
            }
        }
    } else {
        //search is hidden
        if ([self.navigationItem.rightBarButtonItems count] == 1) {
            self.navigationItem.titleView = nil;
            //TODO: The next button should launch into a settings screen...not implemented yet
            //so for now, the action is nil
            UIBarButtonItem * ubc = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:nil];
            self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:self.navigationItem.rightBarButtonItem,ubc, nil];
        }
    }
*/
}

- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // Get the Generic view controller from the stoary board
    /* GenericTableViewController *gvc = [[CommonAPI  class] targetViewControllerFrom:self
     forPath:CLINICALTRIALGOV
     side:LEFT
     returningViewController:GENERICVIEWCONTROLLER];
     */
    // Get the search view controller from the story board
    
    //SearchViewController *svc = [[CommonAPI class] targetViewControllerFrom:self
    //                                                                forPath:CLINICALTRIALGOV
    //                                                                   side:LEFT
    //                                                returningViewController:SEARCHVIEWCONTROLLER];
    //
    //
    // Add to the indexPath collections based on the controller in left
    //
#define viewControllerUsable(x,y,z) "x && ![x isEqual:[NSNull null]] && [x isKindOfClass:[y class]] && x.z.window"
    /*
     if (gvc && ![gvc isEqual:[NSNull null]] && [gvc isKindOfClass:[GenericTableViewController class]] &&
     gvc.tableView.window) {
     
     gvc.indexPaths = [[CommonAPI class] searchTableViewInSearchViewController:gvc
     searchText:searchBar.text];
     if ([gvc.indexPaths count]) {
     gvc.searchIndex = 0;
     [gvc.tableView selectRowAtIndexPath:[gvc.indexPaths objectAtIndex:gvc.searchIndex]
     animated:YES
     scrollPosition:UITableViewScrollPositionMiddle];
     
     [gvc.tableView cellForRowAtIndexPath:[gvc.indexPaths objectAtIndex:gvc.searchIndex]].selected = YES;
     // Make the annotation appear on the map animated
     [gvc refreshMap:[[CommonAPI class] targetViewControllerFrom:self forPath:NA side:RIGHT returningViewController:CLINICALCOLLECTIONSVIEWCONTROLLER]
     forIndexPath:[gvc.indexPaths objectAtIndex:gvc.searchIndex]];
     gvc.searchIndex ++;
     }
     
     }
     */
    [[CommonAPI class] clearKeyboardAndSearchText:self];
}

- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchText
{
    
    GenericTableViewController *gvc = [[CommonAPI  class] targetViewControllerFrom:self
                                                                           forPath:CLINICALTRIALGOV
                                                                              side:LEFT
                                                           returningViewController:GENERICVIEWCONTROLLER];
    // Get the search view controller from the story board
    
    //SearchViewController *svc = [[CommonAPI class] targetViewControllerFrom:self
    //                                                                forPath:CLINICALTRIALGOV
    //                                                                   side:LEFT
    //                                                returningViewController:SEARCHVIEWCONTROLLER];
    //
    //
    // Add to the indexPath collections based on the controller in left
    //
#define viewControllerUsable(x,y,z) "x && ![x isEqual:[NSNull null]] && [x isKindOfClass:[y class]] && x.z.window"
    
    if (gvc && ![gvc isEqual:[NSNull null]] && [gvc isKindOfClass:[GenericTableViewController class]] &&
        gvc.tableView.window) {
        
        if ([searchText isEqualToString:@""]) {
            gvc.filterSet = NO;
            [gvc.filteredListContent removeAllObjects];
            [gvc.tableView reloadData];
            [[CommonAPI class] clearKeyboardAndSearchText:self];
            return;
        }
        
        NSDictionary *cache = [[NSDictionary alloc] initWithDictionary:gvc.filteredListContent];
        NSDictionary *tempDictionary;
        
        [gvc.filteredListContent removeAllObjects];
        gvc.filterSet = NO;
        tempDictionary = [[CommonAPI class] searchData:self.search
                                       searchText:searchBar.text];
        if ([[tempDictionary allKeys] count]) {
            gvc.filterSet = YES;
            [gvc.filteredListContent addEntriesFromDictionary:tempDictionary];
        }
        if (gvc.filterSet && ![gvc.filteredListContent isEqual:cache]) {
            [gvc.tableView reloadData];
        }
        else if(!gvc.filterSet) {
            [gvc.filteredListContent removeAllObjects];
            gvc.filterSet = NO;
            [gvc.tableView reloadData];
            
        }
        
    }
    
}
#pragma mark -- Map view deletegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView
            viewForAnnotation:(id<MKAnnotation>)annotation {
    
    MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MapVC"];
    
    if (!aView) {
        aView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MapVC"];
    }
    ClinicalAnnotation *clinicalAnnotation = (ClinicalAnnotation *) annotation;
    
    if (clinicalAnnotation.primary) {
        aView.canShowCallout = YES;
        ((MKPinAnnotationView *)aView).animatesDrop = NO;
        ((MKPinAnnotationView *)aView).pinColor = MKPinAnnotationColorGreen;
        
    }
    else {
        aView.canShowCallout = YES;
        ((MKPinAnnotationView *)aView).animatesDrop = NO;
        ((MKPinAnnotationView *)aView).pinColor = MKPinAnnotationColorRed;
        aView.selected = YES;
    }
    
    if(!clinicalAnnotation.noAccessory)
    {
        aView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        aView.rightCalloutAccessoryView.tag = 1;
        if (clinicalAnnotation.hasAnalytics){
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
            [button setBackgroundColor:[UIColor yellowColor]];
            [button setImage:[UIImage imageNamed:@BAR_CHART_IMAGE] forState:UIControlStateNormal];
            aView.leftCalloutAccessoryView = button;
            aView.leftCalloutAccessoryView.tag = 2;
        }
    }
    else
        aView.rightCalloutAccessoryView = nil;
    
    aView.annotation = annotation;
    
    return aView;
}


- (void) mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view
calloutAccessoryControlTapped:(UIControl *)control
{
    //
    // Based on the control tag either segue to GraphViewController or
    // Clinical Collections Site Controller
    //
    switch ([control tag]) {
        case 2:
            [self performSegueWithIdentifier:@COLLECTIONS sender:view];
            break;
        case 1:
            //[self performSegueWithIdentifier:@CLINICAL_COLLECTIONS sender:view];
            [self performSegueWithIdentifier:@"ViewStudy" sender:view];
            break;
        default:
            break;
    }
    
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Segue to the ClinicalCollections Web site Lilly COI
    //
    if ([segue.destinationViewController isKindOfClass:[ClinTrialWebViewController class]]) {
        ((ClinTrialWebViewController *)[segue destinationViewController]).url = [NSString stringWithFormat:@CLINICAL_COLLECTIONS_URL, [[sender annotation] title]];
        ClinicalTrialGov *clinicalTrialGov = [[CommonAPI class]
                                              clinicalTrialGov:[NSString stringWithFormat:@"%@", [[sender annotation] title]]
                                              fromSearch:self.search];
        if (clinicalTrialGov == nil || !clinicalTrialGov) {
            self.search = [[ClinicalTrialGov class] SearchForClinicalTrialGov:[[sender annotation] title]
                                                                      context:[[DatabaseHelper class] database].managedObjectContext];
            clinicalTrialGov = [[CommonAPI class]
                                clinicalTrialGov:[NSString stringWithFormat:@"%@", [[sender annotation] title]]
                                fromSearch:self.search];
        }
        [[CommonAPI class] addRecents:clinicalTrialGov.nctID
                               search:clinicalTrialGov.search.searchString];
        
    }
    else if ([segue.destinationViewController isKindOfClass:[CCViewStudyViewController class]]) {
        CCViewStudyViewController * destVC = (CCViewStudyViewController*)segue.destinationViewController;

        [destVC loadViewDataByNtcID:[[sender annotation] title] fromSearch:self.search];
        
    }
    else if ([segue.destinationViewController isKindOfClass:[GraphViewController class]]){
        ClinicalTrialGov *clinicalTrialGov = [[CommonAPI class]
                                              clinicalTrialGov:[NSString stringWithFormat:@"%@", [[sender annotation] title]]
                                              fromSearch:self.search];
        if (clinicalTrialGov == nil || !clinicalTrialGov) {
            self.search = [[ClinicalTrialGov class] SearchForClinicalTrialGov:[[sender annotation] title]
                                                                      context:[[DatabaseHelper class] database].managedObjectContext];
            clinicalTrialGov = [[CommonAPI class]
                                clinicalTrialGov:[NSString stringWithFormat:@"%@", [[sender annotation] title]]
                                fromSearch:self.search];
        }
        [[CommonAPI class] addRecents:clinicalTrialGov.nctID
                               search:clinicalTrialGov.search.searchString];
        ((GraphViewController *)segue.destinationViewController).clinicalTrialGov = clinicalTrialGov;
        
    }
    else if([segue.destinationViewController isKindOfClass:[RecentViewsController class]])
    {   
            
            if ([segue isKindOfClass:[UIStoryboardPopoverSegue class]]) {
                UIStoryboardPopoverSegue *popoverSegue = (UIStoryboardPopoverSegue *)segue;
                [self.popOverController dismissPopoverAnimated:YES];
                self.popOverController = popoverSegue.popoverController;
            }
    }
       
}

#pragma mark -- Split view controller delegate

- (BOOL)splitViewController:(UISplitViewController *)svc
   shouldHideViewController:(UIViewController *)vc
              inOrientation:(UIInterfaceOrientation)orientation
{
    return UIInterfaceOrientationIsPortrait(orientation)?YES:NO;
}

- (void)splitViewController:(UISplitViewController *)svc
     willHideViewController:(UIViewController *)aViewController
          withBarButtonItem:(UIBarButtonItem *)barButtonItem
       forPopoverController:(UIPopoverController *)pc
{
    barButtonItem.title = @STUDIES_TITLE;
    self.barButtonItem = barButtonItem;
}
- (void)setBarButtonItem:(UIBarButtonItem *)barButtonItem {
    
    if (_barButtonItem != barButtonItem) {
        [self handleBarButtonItem:barButtonItem];
    }
}
-(void)splitViewController:(UISplitViewController *)svc
    willShowViewController:(UIViewController *)aViewController
 invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
    self.barButtonItem = nil;
}

- (void)handleBarButtonItem:(UIBarButtonItem *) barButtonItem
{
    self.navigationItem.leftBarButtonItem = barButtonItem;
    _barButtonItem = barButtonItem;
    [self.view setNeedsDisplay];
}

@end
